package com.lightsaber.trade.cloth.common.web.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.util.StrutsTypeConverter;

public class DateConverter extends StrutsTypeConverter {

    private static String DATE_TIME_FOMART = "yyyy-MM-dd HH:mm:ss";

    private static String DATE_FOMART = "dd/MM/yyyy";

    @Override
    public Object convertFromString(final Map context, final String[] values, final Class toClass) {
        Date date = null;

        String dateString = null;

        if (values != null && values.length > 0) {

            dateString = values[0];

            if (dateString != null) {

                SimpleDateFormat format = new SimpleDateFormat(DATE_FOMART);

                try {

                    date = format.parse(dateString);

                } catch (ParseException e) {

                    date = null;

                }

                if (date == null) {

                    format = new SimpleDateFormat(DATE_TIME_FOMART);

                    try {

                        date = format.parse(dateString);

                    } catch (ParseException e) {

                        date = null;

                    }

                }

            }

        }

        return date;
    }

    @Override
    public String convertToString(final Map context, final Object o) {
        Date date = (Date) o;

        String dateString = null;

        if (date != null) {

            SimpleDateFormat format = new SimpleDateFormat(DATE_FOMART);

            dateString = format.format(date);

            if (StringUtils.isBlank(dateString)) {

                format = new SimpleDateFormat(DATE_TIME_FOMART);

                dateString = format.format(date);

            }

        }

        return dateString;
    }

}
